/*
 * Logger.java
 *
 * Created on 12 de Julho de 2009, 19:16
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package necticadastro;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author Netto
 */
public class Logger {
    private static String LogFileName = "";
    private File arquivo;
    private FileOutputStream fos;
    private FileInputStream fis;
    private static Logger SingletonInstance = null;
    /** Creates a new instance of Logger */
    private Logger() {
        LogFileName = "CadastroACL_" + new SimpleDateFormat("dd-MM-yyyy").format(new Date()) + ".txt";
        try {
          // Gravando no arquivo
          File LogDir = new File(System.getProperty("user.dir") + "\\Logs\\");
          if (LogDir.exists()) {
              arquivo = new File(LogDir + "\\" + LogFileName);
              fos = new FileOutputStream(arquivo, true);
          }
          else {
              if (LogDir.mkdir()) {
                  arquivo = new File(LogDir + "\\" + LogFileName);
                  fos = new FileOutputStream(arquivo, true);
              }
              else {
                  arquivo = new File(LogFileName);
                  fos = new FileOutputStream(arquivo, true);
              }
          }
       }
       catch (Exception ex) {
          ex.printStackTrace();
       }
    }
    
    public static Logger getInstance() {
        if (SingletonInstance == null)
            SingletonInstance = new Logger();
        return SingletonInstance;
    }
    
    public void Log(String texto) {
        if (texto != null) {
            try {
                texto += "\n";
                fos.write(texto.getBytes());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    public void LogHeader() {
        String Header = "";
        Log("###########################################################################");
        Header = "Hora: " + new SimpleDateFormat("hh:mm:ss").format(new Date()) + "\n";
        try {
            fos.write(Header.getBytes());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void LogException(Exception trace) {
        LogHeader();
        StackTraceElement[] stackTrace = trace.getStackTrace();
        int i;
        Log("ERRO: " + trace.getMessage());
        Log("--------------------------------------------------------------------------");
        for (i = 0; i < stackTrace.length; i++)
            Log(stackTrace[i].toString());
    }
    
    public void close() {
        try {
            fos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
